package pl.edu.mimuw.irs.rcp.controller.handler;

import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.RootEditPart;

import pl.edu.mimuw.irs.core.model.design.IRSNodeInterface;
import pl.edu.mimuw.irs.rcp.controller.part.IRSNodeEditPart;

public class ExpandHandler extends AbstractHandler {

	// *** Attributes

	private IRSNodeEditPart nodeEditPart;
	public IRSNodeEditPart getNodeEditPart() {
		return nodeEditPart;
	}
	public void setNodeEditPart(IRSNodeEditPart nodeEditPart) {
		this.nodeEditPart = nodeEditPart;
	}
	
	// *** Methods
/*
	private static String getImage(IRSNodeInterface node) {
		String imageSource = null;
		if (node instanceof Place) imageSource = "icon/place_expand.png";
		else if (node instanceof Transition) imageSource = "icon/tran_expand.png";
		return imageSource;
	}*/
	
	// *** Constructors

	public ExpandHandler(IRSNodeEditPart nodeEditPart) {
		super();
		setNodeEditPart(nodeEditPart);
		//setLabel("expand"); // TODO poprawić na UITexts
	}
	
	// *** Methods
	
	@SuppressWarnings("unchecked")
	private void refresh(EditPart editPart) {
		editPart.refresh();
		List<EditPart> children = editPart.getChildren();
		if (editPart instanceof RootEditPart) {
			for (EditPart childEditPart : children) {
				refresh(childEditPart);
			}
		} else if (editPart instanceof IRSNodeEditPart) {
			IRSNodeEditPart nodeEditPart = (IRSNodeEditPart)editPart;
			IRSNodeInterface node = nodeEditPart.getIRSNode();
			if (node.isExpanded()) {
				for (EditPart childEditPart : children) {
					refresh(childEditPart);
				}
			}
		} else {
			for (EditPart childEditPart : children) {
				childEditPart.refresh();
			}
		}
	}
	
	@Override
	public Object execute(ExecutionEvent event) {
		IRSNodeInterface node = getNodeEditPart().getIRSNode();
		node.setExpanded(true);
		
		EditPart root = getNodeEditPart().getRoot();
		
		refresh(root);
		
		return root;
	}
	
}
